package com.wzh.user.controller;

import java.util.Arrays;
import java.util.Map;

import com.wzh.common.utils.JwtUtil;
import com.wzh.user.util.OssUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.wzh.user.entity.UserEntity;
import com.wzh.user.service.UserService;
import com.wzh.common.utils.PageUtils;
import com.wzh.common.utils.R;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;


/**
 * 
 *
 * @author wzh
 * @email 1281204121@qq.com
 * @date 2022-02-22 09:19:32
 */
@RestController
@RequestMapping("user/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private OssUtils ossUtils;

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = userService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info")
    public R info(HttpServletRequest request){
        String token = request.getHeader("token");
        if (token!=null){
            Claims claims = jwtUtil.parseJWT(token);
            if (claims!=null&&"admin".equals(claims.get("roles"))){
                UserEntity user = userService.getById(claims.getId());
                return R.ok().put("user", user);
            }
        }
        return R.error();
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody UserEntity user){
		userService.register(user);

        return R.ok("注册成功");
    }

    /**
     * 图片上传
     */
    @RequestMapping("/upload")
    public R upload(@RequestParam("file") MultipartFile file) {
        return ossUtils.uploadFile(file);
    }


    /**
     * 登录
     */
    @RequestMapping("/login")
    public R login(@RequestParam String nickname,@RequestParam String password) {
        return userService.login(nickname,password);
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody UserEntity user){
		userService.updateById(user);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] ids){
		userService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

}
